package com.tanhua.server.service;

import com.tanhua.commons.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.db.Visitor;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MomentApi;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.utils.RelativeDateFormat;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Reference;

import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MomentService {
    @Reference
    private MomentApi momentApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Reference
    private CommentApi commentApi;

    public void postMoment(PublishVo publishVo, MultipartFile[] imageContent) {
        //获取用户的id
        Long loginId = UserHolder.getUserId();
        //发布图片到阿里云，遍历图片上传
        List<String> imagList = new ArrayList<>();
        try {
            if (null != imageContent) {
                for (MultipartFile multipartFile : imageContent) {
                    String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
                    imagList.add(url);
                }
            }
        } catch (IOException e) {
            log.info("上传图片失败");
            throw new TanHuaException("发布动态图片失败");

        }
        //复制属性
        Publish publish = new Publish();
        BeanUtils.copyProperties(publishVo, publish);
        publish.setMedias(imagList);
        //设置作者的id
        publish.setUserId(loginId);
        //设置图片的list
        publish.setState(0);
        publish.setSeeType(1);
        publish.setLocationName(publishVo.getLocation());
        //调用api发布
        momentApi.add(publish);
    }

    public PageResult<MomentVo> getMoment(Long page, Long pagesize) {
        //获取用户的登录Id
        Long longUserId = UserHolder.getUserId();
        //调用mongdb查询获取分页结果
        PageResult pageResult = momentApi.findByPage(longUserId, page, pagesize);
        //遍历用户Id
        List<Publish> items = pageResult.getItems();
        List<MomentVo> momentVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(items)) {
            //获取所有动态者的id
            for (Publish item : items) {
                MomentVo vo = new MomentVo();
                UserInfo userInfo = userInfoApi.findUserById(item.getUserId());
                BeanUtils.copyProperties(userInfo, vo);
                vo.setUserId(userInfo.getId());
                vo.setTags(StringUtils.split(userInfo.getTags(), ','));
                BeanUtils.copyProperties(item, vo);
                vo.setId(item.getId().toHexString());
                vo.setImageContent(item.getMedias().toArray(new String[0]));
                vo.setDistance("800M");
                vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
                String key = "publish_like_" + longUserId + "_" + item.getId();
                if (redisTemplate.hasKey(key)) {
                    vo.setHasLiked(1);
                }
                momentVos.add(vo);
            }
        }
        pageResult.setItems(momentVos);
        return pageResult;
    }

    public PageResult<MomentVo> recomMoment(Long page, Long pagesize) {
        //获取用户的登录Id
        Long longUserId = UserHolder.getUserId();
        //调用mongdb查询获取分页结果
        PageResult pageResult = momentApi.queryRecommendPublishList(longUserId, page, pagesize);
        //遍历用户Id
        List<Publish> items = pageResult.getItems();
        List<MomentVo> momentVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(items)) {
            //获取所有动态者的id
            for (Publish item : items) {
                MomentVo vo = new MomentVo();
                UserInfo userInfo = userInfoApi.findUserById(item.getUserId());
                BeanUtils.copyProperties(userInfo, vo);
                vo.setUserId(userInfo.getId());
                vo.setTags(StringUtils.split(userInfo.getTags(), ','));
                BeanUtils.copyProperties(item, vo);
                vo.setId(item.getId().toHexString());
                vo.setImageContent(item.getMedias().toArray(new String[0]));
                vo.setDistance("800M");
                vo.setCreateDate(RelativeDateFormat.format(new Date(item.getCreated())));
                String key = "publish_like_" + longUserId + "_" + item.getId();
                if (redisTemplate.hasKey(key)) {
                    vo.setHasLiked(1);
                }
                momentVos.add(vo);
            }
        }
        pageResult.setItems(momentVos);
        return pageResult;
    }

    public PageResult<MomentVo> queryMyPublishList(Long page, Long pagesize, Long userId) {
        Long loginId = UserHolder.getUserId();
        Long targetUserId = loginId;
        if (null != userId) {
            targetUserId = userId;
        }
        PageResult pageResult = momentApi.findMyPublishLiset(page, pagesize, targetUserId);
        List<Publish> items = pageResult.getItems();
        List<MomentVo> momentVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(items)) {
            UserInfo userById = userInfoApi.findUserById(targetUserId);
            items.forEach(publish -> {
                MomentVo momentVo = new MomentVo();
                momentVo.setImageContent(publish.getMedias().toArray(new String[0]));
                BeanUtils.copyProperties(userById, momentVo);
                momentVo.setUserId(userById.getId());
                momentVo.setTags(StringUtils.split(userById.getTags(), ','));
                BeanUtils.copyProperties(publish, momentVo);
                momentVo.setId(publish.getId().toHexString());
                momentVo.setDistance("800M");
                momentVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
                String key = "publish_like_" + loginId + "_" + publish.getId();
                if (redisTemplate.hasKey(key)) {
                    momentVo.setHasLiked(1);
                }
                String loveKey = "publish_love_" + loginId + "_" + publish.getId();
                if (redisTemplate.hasKey(loveKey)) {
                    momentVo.setHasLoved(1);
                }
                redisTemplate.opsForValue().set(key, "1");
                redisTemplate.opsForValue().set(loveKey, "1");
                momentVoList.add(momentVo);
            });
            pageResult.setItems(momentVoList);
        }
        return pageResult;
    }

    public int like(String publishId) {
        Long loninUserId = UserHolder.getUserId();
        Comment comment = new Comment();
        comment.setTargetId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setTargetType(1);
        comment.setUserId(loninUserId);
        int likeCount = commentApi.save(comment);
        String key = "publish_like_" + loninUserId + "_" + publishId;
        redisTemplate.opsForValue().set(key, "1");
        return likeCount;
    }

    public int dislike(String publishId) {
        Long longUserId = UserHolder.getUserId();
        Comment comment = new Comment();
        comment.setTargetId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setTargetType(1);
        comment.setUserId(longUserId);
        int likeCount = commentApi.remove(comment);
        String key = "publish_like_" + longUserId + "_" + publishId;
        redisTemplate.delete(key);
        return likeCount;
    }

    public int love(String publishId) {
        Long longUserId = UserHolder.getUserId();
        Comment comment = new Comment();
        comment.setTargetId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setTargetType(3);
        comment.setUserId(longUserId);
        int loveCount = commentApi.save(comment);
        String key = "publish_love_" + longUserId + "_" + publishId;
        redisTemplate.opsForValue().set(key, "1");
        return loveCount;
    }

    public int unlove(String publishId) {
        Long longUserId = UserHolder.getUserId();
        Comment comment = new Comment();
        comment.setTargetId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setTargetType(3);
        comment.setUserId(longUserId);
        int loveCount = commentApi.remove(comment);
        String key = "publish_love_" + longUserId + "_" + publishId;
        redisTemplate.delete(key);
        return loveCount;
    }

    public MomentVo findPublishById(String userId) {
        Publish publish = momentApi.findPublishById(userId);
        MomentVo momentVo = new MomentVo();
        momentVo.setImageContent(publish.getMedias().toArray(new String[0]));
        BeanUtils.copyProperties(publish, momentVo);
        UserInfo userById = userInfoApi.findUserById(publish.getUserId());
        momentVo.setUserId(userById.getId());
        momentVo.setTags(StringUtils.split(userById.getTags(), ','));
        BeanUtils.copyProperties(publish, momentVo);
        momentVo.setId(publish.getId().toHexString());
        momentVo.setDistance("800M");
        momentVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        String key = "publish_like_" + userById + "_" + userId;
        if (redisTemplate.hasKey(key)) {
            momentVo.setHasLiked(1);
        }
        String loveKey = "publish_love_" + userById + "_" + userId;
        if (redisTemplate.hasKey(loveKey)) {
            momentVo.setHasLoved(1);
        }
        redisTemplate.opsForValue().set(key, "1");
        redisTemplate.opsForValue().set(loveKey, "1");
        return momentVo;
    }

    public List<VisitorVo> visitors() {
        Long longInUserId = UserHolder.getUserId();
       List<Visitor> visitors= commentApi.findVisitors(longInUserId);
        List<Long> visetorsIdList = visitors.stream().map(Visitor::getVisitorUserId).collect(Collectors.toList());
        List<UserInfo> userInfos = userInfoApi.findByBatchIds(visetorsIdList);
        Map<Long, UserInfo> userInfoMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getId, u -> u));
        List<VisitorVo> visitorVoList =new ArrayList<>();
        if (!CollectionUtils.isEmpty(userInfos)){
        visitorVoList = visitors.stream().map(visitor -> {
            VisitorVo vo = new VisitorVo();
            UserInfo userInfo = userInfoMap.get(visitor.getVisitorUserId());
            BeanUtils.copyProperties(userInfo, vo);
            vo.setFateValue(visitor.getScore().intValue());
            vo.setTags(StringUtils.split(userInfo.getTags(), ','));
            return vo;
        }).collect(Collectors.toList());
        return visitorVoList;
        }
        return visitorVoList;
    }
}
